package com.itheima.store.controller;

import com.itheima.store.entity.User;
import com.itheima.store.service.UserService;
import com.itheima.store.utils.Result;
import com.itheima.store.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
public class UserController {

    @Autowired
    UserService userService;


    @RequestMapping("/user")
    @ResponseBody
    public Result register(String method, User user, HttpServletResponse response) throws UnsupportedEncodingException {

        if("register".equals(method)){
            user.setUid(UUIDUtils.getUUID());
            if(userService.register(user)){
                return new Result(Result.SUCCESS,"注册成功");
            }
            return new Result(Result.FAILS,"注册失败");
        }
        if("login".equals(method)){
            User userFromData = userService.login(user);
            if(userFromData != null){

                Cookie cookie = new Cookie("username", URLEncoder.encode(userFromData.getUsername(),"utf-8"));
                cookie.setMaxAge(60 * 10);
                cookie.setPath("/");
                cookie.setDomain("itheimashop.com");
                response.addCookie(cookie);
                return new Result(Result.SUCCESS,"登陆成功");
            }
            return new Result(Result.FAILS,"登陆失败!用户名或密码错误！");
        }
        if("loginOut".equals(method)){

            // 删除Cookie
            Cookie cookie = new Cookie("username", null);
            cookie.setMaxAge(0);
            cookie.setDomain("itheimashop.com");
            response.addCookie(cookie);

            return new Result(Result.SUCCESS,"退出成功");
        }


        return null;
    }
}
